<template>
  <div class="user">
    <PageSearch
      :searchFormConfig="searchFormConfig"
      @handleResetClick="handleResetClick"
      @handleQueryClick="handleQueryClick"
    />

    <PageTable
      :pageContentConfig="pageContentConfig"
      pageName="users"
      ref="pageContentRef"
      @newBtnClick="handleNewData"
      @editBtnClick="handleEditData"
    />
    <PageModel
      :defaultInfo="defaultInfo"
      ref="pageModelRef"
      pageName="users"
      :modelConfig="modelConfigRef"
    />
  </div>
</template>

<script lang="ts">
import PageSearch from '@/components/PageSearch'
import PageTable from '@/components/PageTable'
import PageModel from '@/components/PageModel'

import { defineComponent, computed } from 'vue'
import { useStore } from 'vuex'

import { searchFormConfig } from './config/searchFormConfig'
import pageContentConfig from './config/pageContentConfig'
import modelConfig from './config/modalConfig'

import { UsePageSearch } from 'hooks/UsePageSearch'
import { UsePageModel } from 'hooks/UsePageModel'
import modalConfig from './config/modalConfig'

export default defineComponent({
  components: { PageSearch, PageTable, PageModel },
  setup() {
    const [pageContentRef, handleResetClick, handleQueryClick] = UsePageSearch()

    //pageModel相关的hook逻辑
    // 处理密码的逻辑
    const newCallback = () => {
      const passwordItem = modelConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = false
    }

    const editCallback = () => {
      const passwordItem = modelConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = true
    }
    // 2.动态添加部门和角色列表
    // 使用computed处理config配置文件不是响应式的问题
    const store = useStore()

    const modelConfigRef = computed(() => {
      const departmentItem = modalConfig.formItems.find(
        (item) => item.field === 'departmentId'
      )
      departmentItem!.options = store.state.entireDepartment.map(
        (item: any) => ({
          label: item.name,
          value: item.id
        })
      )

      const roleItem = modalConfig.formItems.find(
        (item) => item.field === 'roleId'
      )
      roleItem!.options = store.state.entireRole.map((item: any) => ({
        label: item.name,
        value: item.id
      }))

      return modelConfig
    })

    // 3.调用hook获取公共的变量和函数
    const [handleNewData, handleEditData, pageModelRef, defaultInfo] =
      UsePageModel(newCallback, editCallback)
    return {
      searchFormConfig,
      pageContentConfig,
      pageContentRef,
      handleResetClick,
      handleQueryClick,
      modelConfigRef,
      handleNewData,
      handleEditData,
      pageModelRef,
      defaultInfo
    }
  }
})
</script>

<style lang="scss" scoped></style>
